package com.xuyuan.agent.intro;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyOrderService implements InvocationHandler, Serializable {

    private static final long serialVersionUID = -6325701255860672442L;

    private OrderService orderService;

    public ProxyOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * ClassLoader loader   类加载器
     * Class<?>[] interfaces 代理对象类类型
     * InvocationHandler 处理类
     *
     * @param args
     */

    public static void main(String[] args) {
        ProxyOrderService proxyOrderService = new ProxyOrderService(new OrderServiceImpl());
        OrderService orderService = (OrderService) Proxy.newProxyInstance
                (proxyOrderService.getClass().getClassLoader(), proxyOrderService.getClass().getInterfaces(), proxyOrderService);
        orderService.save();
    }

    /**
     * 通过该方法的调用对目标对象进行增强
     *
     * @param proxy  代理类代理的真实代理对象
     * @param method 执行的方法
     * @param args   执行方法的参数
     * @return
     * @throws Throwable
     */

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理前置处理 ...");
        Object returnResult = method.invoke(orderService, args);
        System.out.println("代理后置处理 ...");

        return returnResult;
    }

}
